package com.ccl.iot.device;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.ccl.iot.R;
import com.ccl.iot.dvr.utils.CommonUtils;
import com.ccl.iot.publics.UIUtils;
import com.ccl.iot.views.WaitRegView;

import java.util.Timer;
import java.util.TimerTask;


/**
 * @description：可调灯光的view
 * @author： HD
 * @time：2017/3/7
 */

public class DimmerControlerView extends LinearLayout  {


    //--------------------UI------------------
    private SeekBar mDimmerSB;
    public ImageView mDeviceImg;
    private IOTDimmer mIOTDimmer;
    private WaitRegView mWaitRegView;
    public LinearLayout mCameraLayout;


    //---------------------------data

    private static final int PROGRESS_CHANGED = 0;

    private static final long DELAY = 500;
    private static final long PERIOD = 300;

    private Context mContext;
    private DimmerControler mDimmerControler;
    private Timer mDelayTimer;
    private TimerTask mTimerTask;

    private int mLastProgress;

    public DimmerControlerView(Context context) {
        this(context, null);
    }

    public DimmerControlerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.view_dimmer_controler, this, true);

        mDimmerSB = (SeekBar) findViewById(R.id.seekBar_dimmer);
        mDeviceImg = (ImageView) findViewById(R.id.iv_dimmer);

        mWaitRegView = (WaitRegView) findViewById(R.id.waitregview_dimmer);

        mCameraLayout = (LinearLayout) findViewById(R.id.layout_camera_frame);

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                if (mDimmerControler != null) {
                    Bitmap bitmap = mDimmerControler.getBitmap(mDeviceImg.getWidth(), mDeviceImg.getHeight());
                    mDeviceImg.setImageBitmap(bitmap);
                }
//                LoggerUtil.i("图片的宽度：" + mDeviceImg.getWidth() + "--图片高度：" + mDeviceImg.getHeight());
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        initListener();
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
    }

    private void initListener() {

        mDeviceImg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIOTDimmer != null) {
//                  LoggerUtil.i("点击了");
                    //先打开旋转遮罩
                    CommonUtils.showWaitRegView(mWaitRegView);
                    mIOTDimmer.turn(!mIOTDimmer.isOn());
                }
            }
        });

        mDimmerSB.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                if (fromUser && mIOTDimmer != null) {
//                    mIOTDimmer.setDimmer(progress, false);
//                }

                if (fromUser && mIOTDimmer != null) {
                    mLastProgress = progress;
                    delayPlay(DELAY,PERIOD);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mIOTDimmer != null) {
                    mIOTDimmer.setDimmer(seekBar.getProgress(), true);
                }
                cancelTimerTask();
            }
        });
    }

    private void setDimmer() {
        mIOTDimmer.setDimmer(mLastProgress, false);
    }


    /**
     * 设置设备和设备控制器
     *
     * @param device
     */
    public void setDevice(IOTDimmer device) {
        if (device != null) {
            mIOTDimmer = device;
            mDimmerControler = new DimmerControler(device);
            if (mDimmerControler != null) {
                mDimmerControler.setBackColor(getResources().getColor(R.color.device_controler_bg));

                Bitmap bitmap = null;
                if (mDeviceImg.getWidth() == 0) {
                    bitmap = mDimmerControler.getBitmap(1080, 897);
                } else {
                    bitmap = mDimmerControler.getBitmap(mDeviceImg.getWidth(), mDeviceImg.getHeight());
                }

                //设置图片
                mDeviceImg.setImageBitmap(bitmap);
                //图片切换监听器
                mDimmerControler.setOnBitmapChangeListener(new DeviceControler.OnBitmapChangeListener() {
                    @Override
                    public void onBitmapChange() {
                        CommonUtils.hideWaitRegView(mWaitRegView);
                        updateDimmerImg();
                    }
                });

                device.setOnDimmerTurnListener(new IOTDimmer.OnDimmerTurnListner() {
                    @Override
                    public void onTurn() {
                        updateDimmerSB(mIOTDimmer);
                    }
                });

                updateDimmerSB(device);
            }

        }
    }


    public void updateDimmerImg() {
        UIUtils.postTaskSafely(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = mDimmerControler.getBitmap(mDeviceImg.getWidth(),
                        mDeviceImg.getHeight());
                mDeviceImg.setImageBitmap(bitmap);
            }
        });
    }

    private void updateDimmerSB(final IOTDimmer device) {
        UIUtils.postTaskSafely(new Runnable() {
            @Override
            public void run() {
                short dimmer = device.getDimmer();

                mDimmerSB.setProgress(dimmer);

                if (dimmer == 0) {
                    mDimmerSB.setSelected(false);
                } else {
                    mDimmerSB.setSelected(true);
                }

            }
        });
    }

    /**
     * 获取控制器
     *
     * @return
     */
    public DimmerControler getControler() {
        return mDimmerControler;
    }

    /**
     * 使用时钟线程监听点击事件。如果规定时间内有点击，继续下一次监听，直到没有下一次点击, 并且在handler中取消时钟监听。
     *
     * @param delay 连击间隔
     */
    public void delayPlay(long delay, long period) {

       if (mTimerTask == null) {
           mTimerTask = new TimerTask() {
               @Override
               public void run() {
                   setDimmer();
               }
           };
       }

       if (mDelayTimer == null){
           mDelayTimer = new Timer();
           // 第一个参数为执行的mTimerTask
           // 第二个参数为延迟得事件，这里写1000得意思是 mTimerTask将延迟1秒执行
           // 第三个参数为多久执行一次，这里写1000 表示没1秒执行一次mTimerTask的Run方法
           mDelayTimer.schedule(mTimerTask, delay, period);
       }
    }

    private void cancelTimerTask() {
        if (mTimerTask != null && mDelayTimer != null) {
            mTimerTask.cancel();
            mDelayTimer.cancel();
            mTimerTask = null;
            mDelayTimer = null;
        }
    }
}
